package org.jeecg.modules.dock.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.modules.business.warehouse.entity.WmsInReceiptTaskMaterial;
import org.jeecg.modules.business.warehouse.entity.vo.WmsInReceiptTaskPage;
import org.jeecg.modules.dock.client.MesRequestClient;
import org.jeecg.modules.dock.config.JsonUtils;
import org.jeecg.modules.dock.constant.SystemConstants;
import org.jeecg.modules.dock.entity.DockDataReceiveRecord;
import org.jeecg.modules.dock.entity.DockDataSendRecord;
import org.jeecg.modules.dock.entity.DockTaskRecordMap;
import org.jeecg.modules.dock.entity.mds.request.MdsBaseRequestVO;
import org.jeecg.modules.dock.entity.mds.request.ReceivingColumnMaterialsRequestVO;
import org.jeecg.modules.dock.entity.mes.request.MesBaseRequestVO;
import org.jeecg.modules.dock.entity.mes.request.MesBaseZLRequestVO;
import org.jeecg.modules.dock.enums.BusinessTypeEnum;
import org.jeecg.modules.dock.enums.DockDataStatus;
import org.jeecg.modules.dock.enums.MesInterfaceTypeEnum;
import org.jeecg.modules.dock.enums.MesStatusEnum;
import org.jeecg.modules.dock.handler.StatusFactory;
import org.jeecg.modules.dock.handler.StatusHandler;
import org.jeecg.modules.dock.mapper.DockDataReceiveRecordMapper;
import org.jeecg.modules.dock.mapper.DockDataSendRecordMapper;
import org.jeecg.modules.dock.mapper.DockTaskRecordMapMapper;
import org.jeecg.modules.dock.service.MdsDockingService;
import org.jeecg.modules.dock.service.MesDockingRepeaterService;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.service.WorkFlowService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * mds对接数据服务实现类
 *
 * @author zhoutong
 */
@Slf4j
@Service
@AllArgsConstructor
public class MdsDockingServiceImpl implements MdsDockingService {

    private static final String WAREHOUSE_DOCUMENT_CODE = "rkrw_rule";
    private static final String WAREHOUSE_PARAM = "{\"prefix\":\"RKRW\"}";
    private final DockDataReceiveRecordMapper dockDataReceiveRecordMapper;
    private final MesRequestClient mesRequestClient;
    private final DockDataSendRecordMapper dockDataSendRecordMapper;
    private final WorkFlowService workFlowService;
    private final DockTaskRecordMapMapper dockTaskRecordMapMapper;
    private final MesDockingRepeaterService mesDockingRepeaterService;

    private DockDataReceiveRecord getRecord(Object data) {
        DockDataReceiveRecord dockDataReceiveRecord = new DockDataReceiveRecord();
        dockDataReceiveRecord.setUuid(IdUtil.fastSimpleUUID());
        dockDataReceiveRecord.setSource(SystemConstants.MDS);
        dockDataReceiveRecord.setTarget(SystemConstants.WMS);
//        dockDataReceiveRecord.setBusinessCode(business);
        dockDataReceiveRecord.setData(JsonUtils.toJson(data));
        dockDataReceiveRecord.setReceiveTime(new Date());
        return dockDataReceiveRecord;
    }

    @Override
    public void receivingColumnMaterials(ReceivingColumnMaterialsRequestVO vo) {
        log.info("WMS实时接收到的数据是:{} ", vo);
        // 接收的主料明细，wms,不记录直接发给mes
        MesBaseZLRequestVO mesBaseRequestVO = new MesBaseZLRequestVO();
        BeanUtil.copyProperties(vo, mesBaseRequestVO);
        mesBaseRequestVO.setTaskType(MesInterfaceTypeEnum.DP_TAKE_REPLY.getCode());
        mesBaseRequestVO.setDetails(vo.getDetail());
        log.info(JSON.toJSONString(mesBaseRequestVO));
        mesDockingRepeaterService.updateZLStatus(mesBaseRequestVO);
    }

    @Override
    public void updateStatus(MdsBaseRequestVO vo) {
        log.info("WMS实时接收到的数据是:{} ", vo);
        StatusHandler handler = StatusFactory.createHandler(SystemConstants.MDS);
        handler.handle(vo);
    }


    /**
     * 记录发送mds请求信息
     *
     * @param mesBaseRequestVO
     */
    private void record(MesBaseRequestVO mesBaseRequestVO) {
        DockDataSendRecord sendRecord = new DockDataSendRecord();
        sendRecord.setSource(SystemConstants.WMS);
        sendRecord.setTarget(SystemConstants.MES);
        sendRecord.setBusinessCode(mesBaseRequestVO.getTaskCode());
        sendRecord.setUuid(IdUtil.fastUUID());
        sendRecord.setSendTime(new Date());
        sendRecord.setData(JsonUtils.toJson(mesBaseRequestVO.toString()));
        try {
            sendRecord.setStatus(DockDataStatus.SUCCESS);
            sendRecord.setResultCode(DockDataStatus.SUCCESS.getCode());
            sendRecord.setResultData(DockDataStatus.SUCCESS.getRemark());
        } catch (Exception e) {
            sendRecord.setStatus(DockDataStatus.FAILURE);
            sendRecord.setResultCode(DockDataStatus.FAILURE.getCode());
            sendRecord.setResultData(DockDataStatus.FAILURE.getRemark());
            throw new JeecgBootException("请求mes更新状态接口失败", e);
        } finally {
            dockDataSendRecordMapper.insert(sendRecord);
        }
    }

    private <T extends MesBaseRequestVO> void wmsInReceiptTask(List<WmsInReceiptTaskMaterial> list,
                                                               String recordId,
                                                               String code,
                                                               String documentType,
                                                               T vo,
                                                               String lineName,
                                                               String taskCode,
                                                               String requestPerson,
                                                               Date requestTime) {
        WmsInReceiptTaskPage wmsInReceiptTaskPage = new WmsInReceiptTaskPage();
        wmsInReceiptTaskPage.setDocumentCode(FillRuleUtil.executeRule(WAREHOUSE_DOCUMENT_CODE, JSON.parseObject(WAREHOUSE_PARAM)).toString());
        wmsInReceiptTaskPage.setDocumentType(documentType);
        wmsInReceiptTaskPage.setWmsInReceiptTaskMaterialList(list);
        wmsInReceiptTaskPage.setTaskDate(new Date());
        wmsInReceiptTaskPage.setOriginalSystem(SystemConstants.MES);
        wmsInReceiptTaskPage.setRequestPerson("MES请求人员");
        wmsInReceiptTaskPage.setTaskType(vo.getTaskType());
        wmsInReceiptTaskPage.setSiteCode(vo.getSite());
        if (StrUtil.isNotEmpty(lineName)) {
            wmsInReceiptTaskPage.setProductLine(lineName);
        }
        if (StrUtil.isNotEmpty(taskCode)) {
            wmsInReceiptTaskPage.setTaskCode(taskCode);
        }
//        if (StrUtil.isNotEmpty(requestPerson)) {
//            wmsInReceiptTaskPage.setRequestPerson(requestPerson);
//        }
        if (ObjectUtil.isNotEmpty(requestTime)) {
            wmsInReceiptTaskPage.setRequestTime(requestTime);
        }
        //创建流程
        BaseFlowDto base = new BaseFlowDto();
        base.setDocumentType(documentType);
        base.setCode(code);
        base.setData(wmsInReceiptTaskPage);
        base.setBusinessType(BusinessTypeEnum.document_task.toString());
        workFlowService.commit(base);
        String taskId = base.getInfoId();
        DockTaskRecordMap map = new DockTaskRecordMap();
        map.setTaskId(taskId);
        map.setRecordId(recordId);
        map.setMesTaskCode(vo.getTaskCode());
        map.setSite(vo.getSite());
        dockTaskRecordMapMapper.insert(map);
        updateMesStatus(vo);
    }

    private <T extends MesBaseRequestVO> void updateMesStatus(T vo) {
        MesBaseRequestVO requestVO = new MesBaseRequestVO();
        requestVO.setRemark(vo.getRemark());
        requestVO.setTaskCode(vo.getTaskCode());
        requestVO.setOperateTime(new Date());
        requestVO.setTaskStatus(MesStatusEnum.TASK_STARTED.getCode());
        requestVO.setSite(vo.getSite());
        requestVO.setOperateReason(vo.getOperateReason());
        requestVO.setOperatorName(vo.getOperatorName());
        //mesRequestClient.updateStatus(requestVO);
    }

}
